package com.bmob.lover.ui.fragment.user

import android.content.DialogInterface
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.qmuiteam.qmui.skin.QMUISkinHelper
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.*
import com.theone.common.util.FileUtils
import com.theone.common.widget.datePicker.DateTimePicker
import com.bmob.lover.R
import com.bmob.lover.app.util.getCurrentUser
import com.bmob.lover.data.model.bean.BmobDate
import com.bmob.lover.data.model.bean.User
import com.bmob.lover.data.model.enums.TYPE_REGISTER
import com.bmob.lover.databinding.FragmentUserInfoModifyBinding
import com.bmob.lover.ui.activity.IndexActivity
import com.bmob.lover.ui.fragment.base.BaseFragment
import com.bmob.lover.viewmodel.UploadFileViewModel
import com.bmob.lover.viewmodel.request.UserUpdateViewModel
import com.bmob.lover.viewmodel.state.UserInfoModifyViewModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.theone.mvvm.core.app.ext.addFailTipsObserve
import com.theone.mvvm.core.app.util.glide.GlideEngine
import com.theone.mvvm.ext.qmui.*
import java.util.*

//  ┏┓　　　┏┓
//┏┛┻━━━┛┻┓
//┃　　　　　　　┃
//┃　　　━　　　┃
//┃　┳┛　┗┳　┃
//┃　　　　　　　┃
//┃　　　┻　　　┃
//┃　　　　　　　┃
//┗━┓　　　┏━┛
//    ┃　　　┃                  神兽保佑
//    ┃　　　┃                  永无BUG！
//    ┃　　　┗━━━┓
//    ┃　　　　　　　┣┓
//    ┃　　　　　　　┏┛
//    ┗┓┓┏━┳┓┏┛
//      ┃┫┫　┃┫┫
//      ┗┻┛　┗┻┛
/**
 * @author The one
 * @date 2021-06-23 14:35
 * @describe 完善用户信息
 * @email 625805189@qq.com
 * @remark
 */
class UserInfoModifyFragment private constructor() :
    BaseFragment<UserInfoModifyViewModel, FragmentUserInfoModifyBinding>(),
    OnResultCallbackListener<LocalMedia>,
    DateTimePicker.ResultHandler {

    companion object {
        fun newInstance(type: Int = 666): UserInfoModifyFragment {
            return UserInfoModifyFragment().apply {
                arguments = Bundle().apply {
                    putInt(BundleConstant.TYPE, type)
                }
            }
        }
    }

    private val mType: Int? by getValue(BundleConstant.TYPE, 666)
    private val mUser: User? by lazy {
        getCurrentUser()
    }
    private val mUserRequest: UserUpdateViewModel by viewModels()
    private val mUpdateFileRequest: UploadFileViewModel by viewModels()

    private var mSelectMedia: LocalMedia? = null
    private val sexItems = arrayOf("男", "女")

    private val mDatePicker: DateTimePicker by lazy {
        DateTimePicker(
            mActivity,
            this,
            getYearDate(1970),
            Date(),
            DateTimePicker.Builder(mActivity).apply {
                setOk("确定")
                setOk("确定")
                setCancel("取消")
                setCancelTextColor(Color.RED)
                setOkTextColor(getColor(mActivity, R.color.qmui_config_color_blue))
                setTitleTextColor(getColor(mActivity, R.color.qmui_config_color_gray_3))
                setKeepLastSelected(false)
                setSelectedTextColor(
                    QMUISkinHelper.getSkinColor(
                        getContentView(),
                        R.attr.app_skin_primary_color
                    )
                )
                setShowType(DateTimePicker.ShowType.DAY)
            })
    }

    override fun initView(root: View) {
        getTopBar()?.run {
            if (mType == TYPE_REGISTER) {
                addLeftTextButton("跳过", R.id.qmui_topbar_item_left_back).setOnClickListener {
                    startToIndex()
                }
                setTitle("完善信息")
            } else {
                setTitleWitchBackBtn("修改信息")
            }
            addRightTextButton("完成", R.id.topbar_right_text)?.setOnClickListener {
                updateUserInfo(false)
            }
        }
    }

    override fun initData() {
        mUser?.let {
            with(getViewModel()) {
                it.birthday?.getDate()?.formatString()?.let {
                    birthday.set(it)
                }
                sex.set(it.sex())
                nickname.set(it.nickname)
                icon.set(it.avatar)
            }
        }
    }

    override fun createObserver() {
        addLoadingObserve(mUpdateFileRequest, mUserRequest)
        mUpdateFileRequest.getResponseLiveData().observe(this) {
            getViewModel().icon.set(it[0].path)
            updateUserInfo(true)
        }
        mUserRequest.getObjectSuccessLiveDate().observe(this) {
            mAppVm.setUserInfo(mUser)
            showSuccessTipsDialog(it.msg) {
                if (mType == TYPE_REGISTER) {
                    startToIndex()
                } else {
                    popBackStack()
                }
            }
        }
        addFailTipsObserve(mUserRequest,mUpdateFileRequest)
    }

    private fun updateUserInfo(isUpdateFile: Boolean) {
        getViewModel().run {
            when {
                nickname.get().isEmpty() -> showFailTipsDialog("请填写昵称")
                birthday.get().isEmpty() -> showFailTipsDialog("请选择出生日期")
                icon.get().isEmpty() -> showFailTipsDialog("请选择个头像吧")
                else -> {
                    if (!icon.get().startsWith("http")) {
                        // 不是网络图片，说明是本地选择了，需要先上传文件
                        mSelectMedia?.let {
                            it.isCompressed = false
                            mUpdateFileRequest.uploadFiles(listOf(it))
                        }
                    } else {
                        mUser?.let {
                            it.nickname = nickname.get()
                            it.gender = getSex()
                            it.birthday = BmobDate(birthday.get().formatDate())
                            it.avatar = icon.get()
                            mUserRequest.updateUserInfo(it, isUpdateFile)
                        }
                    }
                }
            }
        }
    }

    override fun handle(date: Date?) {
        date?.let {
            getViewModel().birthday.set(it.formatString())
        }
    }

    override fun onResult(result: ArrayList<LocalMedia>?) {
        result?.let {
            mSelectMedia = it[0]
            getViewModel().icon.set(it[0].availablePath)
        }
    }

    override fun onCancel() {

    }

    private fun startToIndex() {
        startActivity(IndexActivity::class.java, true)
    }

    override fun getBindingClick() = ProxyClick()

    inner class ProxyClick  {

        fun userIcon() {
            PictureSelector.create(this@UserInfoModifyFragment).openGallery(SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(GlideEngine.createGlideEngine())
                .isDirectReturnSingle(true)
                .forResult(this@UserInfoModifyFragment)
        }

        fun birthday() {
            var date = getViewModel().birthday.get()
            if (date.isEmpty()) {
                date = "2000-06-06"
            }
            mDatePicker.show(date.formatDate())
        }

        fun sex() {
            showSexSelectDialog()
        }

    }

    private fun showSexSelectDialog() {
        context?.showSingleChoiceDialog(
            "选择性别",
            sexItems,
            getSex(),
            DialogInterface.OnClickListener { dialog, which ->
                dialog.dismiss()
                getViewModel().sex.set(sexItems[which])
            })
    }

    private fun getSex(): Int {
        var select = -1
        for ((index, item) in sexItems.withIndex()) {
            if (item == getViewModel().sex.get()) {
                select = index
                break
            }
        }
        return select
    }

}